package com.powernode.component;

import com.nimbusds.jose.shaded.json.JSONObject;
import com.powernode.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 登录认证时token无效或过期的处理器
 */
@Component
public class CustomAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        // 获取response对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应头的数据类型为json
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 设置响应状态码
        response.setStatusCode(HttpStatus.OK);
        // 使用oauth2 的工具类库的JSONObject类创建一个对象用于设置响应信息
        JSONObject params = new JSONObject();
        params.put("code",HttpStatus.UNAUTHORIZED.value());
        params.put("msg","token无效或过期");
        // 包装响应信息
        DataBuffer buffer = response.bufferFactory().wrap(params.toJSONString().getBytes(StandardCharsets.UTF_8));
        // 响应给前端
        return response.writeWith(Mono.just(buffer));
    }
}
